<template>
  <t-card :bordered="false">
    <div style="margin-bottom: var(--td-comp-margin-xxl);display: flex; justify-content: space-between;">
      <div style="display: flex;">
        <t-radio-group v-model="defaultCompany" theme="button"  @change="hanldeChangeSelect" style="margin-right: 10px;">
          <t-radio-button :value="_.id" v-for="_ in companyList">{{ _.name }}</t-radio-button>
        </t-radio-group>
        <t-radio-group v-model="defaultCustomers"   @change="handleTimeChange">
          <t-radio-button v-for="_ in timeDate" :key="'report'+_.value" :value="_.value"> {{ _.name }}</t-radio-button>
        </t-radio-group>
        <t-date-range-picker enable-time-picker v-model="timeRange" allow-input clearable @change="onChange" style="margin-left: 10px;"/>
      </div>
      <t-select
        auto-width
        v-model="select"
        :options="[{label:'人员数据',value:'1'},{label:'平台数据',value:'2'}]"
        placeholder="请选择"
        style="width: 120px;"
        @change="hanldeChangeSelect"
      ></t-select>
    </div>

    <!-- 人员数据 -->
    <t-table 
      v-if="select === '1'" 
      :rowspan-and-colspan="rowspanAndColspan" 
      :data="personnelTableData" 
      :columns="personnelColumns" 
      :pagination="null" 
      row-key="id" 
      size="small" 
      max-height="calc(100vh - 280px)"
      stripe 
      bordered
      :foot-data="personnelFootData"
      >
      <template #saleId="{ row }">
        {{ userStore.getUserNameById(row.saleId) }}
      </template>
      <template #channelSource="{ row }">
        {{ channelList.find((item) => item.id.toString() === row.channelSource)?.name }}
      </template>
      <template #addCount="{ row }">
        <t-link theme="primary" @click="hanldeGoToOrderList(row.addCount)">{{ row.addCount&&row.addCount.split(',').length }}</t-link>
      </template>
      <template #effectivePercent="{ row }">
        <t-link >{{ row.effective&&(row.effective.split(',').length/row.addCount.split(',').length*100).toFixed(2)+'%' }}</t-link>
      </template>
      <template #designer="{ row }">
        <t-link theme="primary" @click="hanldeGoToOrderList(row.designer)">{{ row.designer&&row.designer.split(',').length }}</t-link>
      </template>
      <template #effective="{ row }">
        <t-link theme="primary" @click="hanldeGoToOrderList(row.effective)">{{ row.effective&&row.effective.split(',').length }}</t-link>
      </template>
      <template #deleted="{ row }">
        <t-link theme="primary" @click="hanldeGoToOrderList(row.deleted)">{{ row.deleted&&row.deleted.split(',').length }}</t-link>
      </template>
      <template #contract="{ row }">
        <t-link theme="primary" @click="hanldeGoToOrderList(row.contract)">{{ row.contract&&row.contract.split(',').length }}</t-link>
      </template>
      <template #designerPercent="{ row }">
        <t-link>{{ row.designer&&(row.designer.split(',').length/row.addCount.split(',').length*100).toFixed(2) +'%' }}</t-link>
      </template>
      <template #contractPercent="{ row }">
        <t-link>{{ row.contract&&(row.contract.split(',').length/row.addCount.split(',').length*100).toFixed(2)+'%' }}</t-link>
      </template>
      <template #deletedPercent="{ row }">
        <t-link>{{ row.deleted&&(row.deleted.split(',').length/row.addCount.split(',').length*100).toFixed(2) +'%'}}</t-link>
      </template>
      <template #contractPrice="{ row }">
        <t-link>{{ row.contractPrice&&row.contractPrice}}</t-link>
      </template>
    </t-table>
    <t-table 
      v-if="select === '2'" 
      :data="platformTableData" 
      :columns="platformColumns" 
      :pagination="null" 
      row-key="id" 
      size="small" 
      max-height="calc(100vh - 280px)"
      stripe 
      bordered
      :foot-data="platformFootData"
      >
      <template #saleId="{ row }">
        {{ userStore.getUserNameById(row.saleId) }}
      </template>
      <template #channel_source="{ row }">
        {{ channelList.find((item) => item.id.toString() === row.channel_source)?.name }}
      </template>
      <template #addCount="{ row }">
        <t-link theme="primary" @click="hanldeGoToOrderList(row.addCount)">{{ row.addCount&&row.addCount.split(',').length }}</t-link>
      </template>
      <template #effectivePercent="{ row }">
        <t-link >{{ row.effective&&(row.effective.split(',').length/row.addCount.split(',').length*100).toFixed(2)+'%' }}</t-link>
      </template>
      <template #designer="{ row }">
        <t-link theme="primary" @click="hanldeGoToOrderList(row.designer)">{{ row.designer&&row.designer.split(',').length }}</t-link>
      </template>
      <template #effective="{ row }">
        <t-link theme="primary" @click="hanldeGoToOrderList(row.effective)">{{ row.effective&&row.effective.split(',').length }}</t-link>
      </template>
      <template #deleted="{ row }">
        <t-link theme="primary" @click="hanldeGoToOrderList(row.deleted)">{{ row.deleted&&row.deleted.split(',').length }}</t-link>
      </template>
      <template #contract="{ row }">
        <t-link theme="primary" @click="hanldeGoToOrderList(row.contract)">{{ row.contract&&row.contract.split(',').length }}</t-link>
      </template>
      <template #designerPercent="{ row }">
        <t-link>{{ row.designer&&(row.designer.split(',').length/row.addCount.split(',').length*100).toFixed(2) +'%' }}</t-link>
      </template>
      <template #contractPercent="{ row }">
        <t-link>{{ row.contract&&(row.contract.split(',').length/row.addCount.split(',').length*100).toFixed(2)+'%' }}</t-link>
      </template>
      <template #deletedPercent="{ row }">
        <t-link>{{ row.deleted&&(row.deleted.split(',').length/row.addCount.split(',').length*100).toFixed(2) +'%'}}</t-link>
      </template>
      <template #contractPrice="{ row }">
        <t-link>{{ row.contractPrice&&row.contractPrice}}</t-link>
      </template>
    </t-table>

  </t-card>
</template>

<script lang="ts">
export default {
  name: 'AcquireCustomers',
};
</script>

<script setup lang="ts">
import dayjs from 'dayjs';
import { MessagePlugin, TableCol } from 'tdesign-vue-next';
import { computed, nextTick, onMounted, onUpdated, reactive, Ref, ref, watch } from 'vue';

import { getProductCollection } from '@/api/finance/product-collection';
import { getCompanyList, getSimpleDeptList } from '@/api/system/dept';
import { propertyManageCRUD } from '@/api/config/property';
import CustomTable from '@/components/custom/table/index.vue';

import { useDictionaryStore, useUserStore } from '@/store';
import { getUserListByRoleCode } from '@/api/system/user';
import listToTree from '@/utils/listToTree';
import disposableParams from '@/utils/disposableParams';
import { homeHuokeData, homeHuokePlatform } from '@/api/dashboard/base';
import { channelManageCRUD } from '@/api/config/common-config';
import { useRouter } from 'vue-router';
// 路由器
const router = useRouter();
// 字典仓库
const dictionaryStore = useDictionaryStore();
// 用户仓库
const userStore = useUserStore();

// Select value for table switching
const select = ref('1');
// 公司列表
const companyList = ref([]);
// 默认公司
const defaultCompany = ref()
// 处理获取公司列表
const handleGetCompanyList = () => {
  getCompanyList()
    .then((data) => {
      companyList.value = data;
      defaultCompany.value = data[0].id
      handleGetDesigerRank()
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
};
// handleGetCompanyList();
// 时间默认
const defaultCustomers = ref(1)
const handleGetDesigerRank = () => {
  const params = {
    beginTime:'',
    endTime:'',
    companyId:defaultCompany.value
  }
  const now = new Date();
  
  switch(defaultCustomers.value) {
    case 1: // 本周
      const firstDayOfWeek = new Date(now.setDate(now.getDate() - now.getDay() + (now.getDay() === 0 ? -6 : 1)));
      const lastDayOfWeek = new Date(firstDayOfWeek);
      lastDayOfWeek.setDate(firstDayOfWeek.getDate() + 6);
      
      params.beginTime = dayjs(firstDayOfWeek).format('YYYY-MM-DD 00:00:00');
      params.endTime = dayjs(lastDayOfWeek).format('YYYY-MM-DD 23:59:59');
      break;
      
    case 2: // 本月
      const firstDayOfMonth = new Date(now.getFullYear(), now.getMonth(), 1);
      const lastDayOfMonth = new Date(now.getFullYear(), now.getMonth() + 1, 0);
      
      params.beginTime = dayjs(firstDayOfMonth).format('YYYY-MM-DD 00:00:00');
      params.endTime = dayjs(lastDayOfMonth).format('YYYY-MM-DD 23:59:59');
      break;
      
    case 3: // 本年
      const firstDayOfYear = new Date(now.getFullYear(), 0, 1);
      const lastDayOfYear = new Date(now.getFullYear(), 11, 31);
      
      params.beginTime = dayjs(firstDayOfYear).format('YYYY-MM-DD 00:00:00');
      params.endTime = dayjs(lastDayOfYear).format('YYYY-MM-DD 23:59:59');
      break;
      
    case 4: // 全部
      // 不传日期参数
      params.beginTime='';
      params.endTime='';
      break;
  }
    if(timeRange.value.length>0) {
     params.beginTime=timeRange.value[0];
    params.endTime=timeRange.value[1];
  }
    homeHuokeData(params).then((data) => {
      personnelTableData.value = data
      console.log(personnelTableData.value,'designerRank');
      
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
}
const handleGetPlatForm = () => {
   const params = {
    beginTime:'',
    endTime:'',
    companyId:defaultCompany.value
  }
  const now = new Date();
  
  switch(defaultCustomers.value) {
    case 1: // 本周
      const firstDayOfWeek = new Date(now.setDate(now.getDate() - now.getDay() + (now.getDay() === 0 ? -6 : 1)));
      const lastDayOfWeek = new Date(firstDayOfWeek);
      lastDayOfWeek.setDate(firstDayOfWeek.getDate() + 6);
      
      params.beginTime = dayjs(firstDayOfWeek).format('YYYY-MM-DD 00:00:00');
      params.endTime = dayjs(lastDayOfWeek).format('YYYY-MM-DD 23:59:59');
      break;
      
    case 2: // 本月
      const firstDayOfMonth = new Date(now.getFullYear(), now.getMonth(), 1);
      const lastDayOfMonth = new Date(now.getFullYear(), now.getMonth() + 1, 0);
      
      params.beginTime = dayjs(firstDayOfMonth).format('YYYY-MM-DD 00:00:00');
      params.endTime = dayjs(lastDayOfMonth).format('YYYY-MM-DD 23:59:59');
      break;
      
    case 3: // 本年
      const firstDayOfYear = new Date(now.getFullYear(), 0, 1);
      const lastDayOfYear = new Date(now.getFullYear(), 11, 31);
      
      params.beginTime = dayjs(firstDayOfYear).format('YYYY-MM-DD 00:00:00');
      params.endTime = dayjs(lastDayOfYear).format('YYYY-MM-DD 23:59:59');
      break;
      
    case 4: // 全部
      // 不传日期参数
      params.beginTime='';
      params.endTime='';
      break;
  }
    if(timeRange.value.length>0) {
     params.beginTime=timeRange.value[0];
    params.endTime=timeRange.value[1];
  }
    homeHuokePlatform(params).then((data) => {
      platformTableData.value = data
      console.log(platformTableData.value,'platformTableData');
      
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
}
const handleTimeChange = () => {
  timeRange.value = []
  hanldeChangeSelect()
}
// 日期选择
const timeRange = ref([])
const onChange = (value, context) => {
  const params = {
    beginTime:'',
    endTime:'',
    companyId:defaultCompany.value
  }
  if(value.length>0) {
    params.beginTime=value[0];
    params.endTime=value[1];
    defaultCustomers.value = 0
  } else {
    params.beginTime='';
    params.endTime='';
    defaultCustomers.value = 4
  }
 hanldeChangeSelect()
}
// 渠道列表
const channelList = ref([]);
// 处理获取渠道列表
const handleGetChannelList = () => {
  const params = {
    pageSize: -1,
  };
  channelManageCRUD
    .page(params)
    .then((data) => {
      channelList.value = data.list;
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
};
handleGetChannelList();
const hanldeChangeSelect=() => {
  if(select.value==='1') {
    handleGetDesigerRank()
  } else {
    handleGetPlatForm()
  }
}
// 精简部门列表
const simpleDeptList = ref([]);
// 精简部门树
const simpleDeptTree = ref([]);
// 处理获取精简部门
const handleGetSimpleDeptTree = () => {
  getSimpleDeptList().then((data) => {
    simpleDeptList.value = data;
    simpleDeptTree.value = listToTree(data);
  });
};
handleGetSimpleDeptTree();

// 使用两个独立的ref来存储表格数据
const personnelTableData = ref([]);
const platformTableData = ref([]);

// 人员数据表格列
const personnelColumns: TableCol[] = [
  {colKey:'id',title:'获客部' , align:'center',thClassName:'fw-b',children:[
    { colKey: 'saleId', title: '人员', align:'center'},
    { colKey: 'channelSource', title: '渠道', align:'center' },
    { colKey: 'addCount', title: '新增', align:'center' },
    { colKey: 'effective', title: '有效',align:'center' },
    { colKey: 'effectivePercent', title: '有效率',align:'center' },
    { colKey: 'deleted', title: '废单',align:'center'},
    { colKey: 'deletedPercent', title: '废单率',align:'center'},
    { colKey: 'designer', title: '转设计师',align:'center'},
    { colKey: 'designerPercent', title: '转设计师率',align:'center'},
    { colKey: 'contract', title: '签单',align:'center'},
    { colKey: 'contractPercent', title: '签约率',align:'center'},
    { colKey: 'contractPrice', title: '合同金额',align:'center'},
    { colKey: 'zsjmb', title: '转设计目标',align:'center'},
    { colKey: 'zsjwc', title: '转设计完成',align:'center'},
  ]}
  

];
const rowspanAndColspan = ({ row ,col, rowIndex, colIndex }) => {
 // 合并人员名称列
 if (col.colKey === 'saleId') {
    // 如果是当前人员的第一行数据
    if (rowIndex === 0 || personnelTableData.value[rowIndex].saleId !== personnelTableData.value[rowIndex - 1].saleId) {
      // 计算当前人员有多少行数据
      let rowspan = 1;
      for (let i = rowIndex + 1; i < personnelTableData.value.length; i++) {
        if (personnelTableData.value[i].saleId === row.saleId) {
          rowspan++;
        } else {
          break;
        }
      }
      return { rowspan, colspan: 1 };
    } else {
      return { rowspan: 0, colspan: 0 };
    }
  }
  
  // 合并转设计目标和转设计完成列
  if (col.colKey === 'zsjmb' || col.colKey === 'zsjwc') {
    // 如果是当前人员的第一行数据
    if (rowIndex === 0 || personnelTableData.value[rowIndex].saleId !== personnelTableData.value[rowIndex - 1].saleId) {
      // 计算当前人员有多少行数据
      let rowspan = 1;
      for (let i = rowIndex + 1; i < personnelTableData.value.length; i++) {
        if (personnelTableData.value[i].saleId === row.saleId) {
          rowspan++;
        } else {
          break;
        }
      }
      // 只有当值相同时才合并
      const currentValue = row[col.colKey];
      let actualRowspan = 1;
      for (let i = rowIndex + 1; i < rowIndex + rowspan; i++) {
        if (personnelTableData.value[i][col.colKey] === currentValue) {
          actualRowspan++;
        } else {
          break;
        }
      }
      return { rowspan: actualRowspan, colspan: 1 };
    } else {
      // 检查是否需要跳过（因为已经被合并）
      for (let i = rowIndex - 1; i >= 0; i--) {
        if (personnelTableData.value[i].saleId === row.saleId) {
          if (personnelTableData.value[i][col.colKey] === row[col.colKey]) {
            return { rowspan: 0, colspan: 0 };
          }
          break;
        }
      }
      return { rowspan: 1, colspan: 1 };
    }
  }
};
// 平台数据表格列 (customize as needed)
const platformColumns: TableCol[] = [
    {colKey:'id',title:'获客部' , align:'center',thClassName:'fw-b',children:[
      { colKey: 'channel_source', title: '渠道', align:'center' },
      { colKey: 'addCount', title: '新增', align:'center' },
      { colKey: 'effective', title: '新增有效', align:'center' },
      { colKey: 'effectivePercent', title: '有效率', align:'center' },
      { colKey: 'deleted', title: '废单',align:'center'},
      { colKey: 'deletedPercent', title: '废单率',align:'center'},
      { colKey: 'designer', title: '转设计师', align:'center'},
      { colKey: 'designerPercent', title: '转设计师率', align:'center'},
      { colKey: 'contract', title: '合同', align:'center'},
      { colKey: 'contractPercent', title: '转化率', align:'center'},
      { colKey: 'contractPrice', title: '产值', align:'center'},
    ]}
  
];

const hanldeGoToOrderList = (orderIds:string) => {
  if(!orderIds) return
  disposableParams.set('to-do-tree-jump-params', {
  
    orderIds: orderIds,
   
  });
  router.push({ path:'/order/basic', query: { timeStamp: new Date().getTime() } });
}


onMounted(() => {
  handleGetCompanyList()
});

const calculateSummaryP = (colKey: string) => {
   if (!platformTableData.value.length) return 0;
  
  // 处理计数字段（如新增数、有效数等）
  if (['addCount', 'effective', 'designer', 'contract', 'deleted'].includes(colKey)) {
    return platformTableData.value.reduce((sum, row) => sum + (row[colKey] ? row[colKey].split(',').length : 0), 0);
  }
  
  // 处理百分比字段（如有效率、转设计率等）
  if (colKey.endsWith('Percent')) {
    const baseField = colKey.replace('Percent', '');
    const countField = 'addCount';
    const total = platformTableData.value.reduce((sum, row) => sum + (row[countField] ? row[countField].split(',').length : 0), 0);
    const part = platformTableData.value.reduce((sum, row) => sum + (row[baseField] ? row[baseField].split(',').length : 0), 0);
    return total > 0 ? (part / total * 100).toFixed(2) + '%' : '0%';
  }
  
  // 处理金额字段
  if (colKey === 'contractPrice') {
    return platformTableData.value.reduce((sum, row) => sum + (parseFloat(row[colKey]) || 0), 0).toFixed(2);
  }
  
  return 0;
};

// 计算汇总值
const calculateSummary = (colKey: string) => {
  if (!personnelTableData.value.length) return 0;
  
  // 处理计数字段（如新增数、有效数等）
  if (['addCount', 'effective', 'designer', 'contract', 'deleted'].includes(colKey)) {
    return personnelTableData.value.reduce((sum, row) => sum + (row[colKey] ? row[colKey].split(',').length : 0), 0);
  }
  
  // 处理百分比字段（如有效率、转设计率等）
  if (colKey.endsWith('Percent')) {
    const baseField = colKey.replace('Percent', '');
    const countField = 'addCount';
    const total = personnelTableData.value.reduce((sum, row) => sum + (row[countField] ? row[countField].split(',').length : 0), 0);
    const part = personnelTableData.value.reduce((sum, row) => sum + (row[baseField] ? row[baseField].split(',').length : 0), 0);
    return total > 0 ? (part / total * 100).toFixed(2) + '%' : '0%';
  }
  
  // 处理金额字段
  if (colKey === 'contractPrice') {
    return personnelTableData.value.reduce((sum, row) => sum + (parseFloat(row[colKey]) || 0), 0).toFixed(2);
  }
  
  return 0;
};

// 人员数据表尾汇总行
const personnelFootData = computed(() => {
  if (!personnelTableData.value.length) return [];
  
  return [
    {
      saleId: '人员汇总',
      addCount: calculateSummary('addCount'),
      effective: calculateSummary('effective'),
      effectivePercent: calculateSummary('effectivePercent'),
      designer: calculateSummary('designer'),
      designerPercent: calculateSummary('designerPercent'),
      contract: calculateSummary('contract'),
      contractPercent: calculateSummary('contractPercent'),
      contractPrice: calculateSummary('contractPrice'),
      deleted: calculateSummary('deleted'),
      deletedPercent: calculateSummary('deletedPercent'),
      // 汇总行中这些字段留空
      channelSource: '',
      zsjmb: '',
      zsjwc: ''
    }
  ];
});
// 平台数据表尾
const platformFootData = computed(() => {
  return [
    {
      channel_source: '平台汇总',
      addCount: calculateSummaryP('addCount'),
      effective: calculateSummaryP('effective'),
      effectivePercent: calculateSummaryP('effectivePercent'),
      designer: calculateSummaryP('designer'),
      designerPercent: calculateSummaryP('designerPercent'),
      contract: calculateSummaryP('contract'),
      contractPercent: calculateSummaryP('contractPercent'),
      contractPrice: calculateSummaryP('contractPrice'),
      deleted: calculateSummaryP('deleted'),
      deletedPercent: calculateSummaryP('deletedPercent'),
    },
  ];
});

const timeDate = [
  {value:1,name:'本周'},
  {value:2,name:'本月'},
  {value:3,name:'本年'},
  {value:4,name:'全部'},
  ]
</script>

<style lang="less" scoped>
:deep(.t-table__footer) {
  td {
    text-align: center !important;
  }
}
:deep(.fw-b) {
  font-weight: bold;
}
</style>